<template>
    <div class="index-list-step-container">
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:2600, y: tableHeight}"
        bordered
        rowKey="id"
        :pagination="false"
        :columns="columns"
        :dataSource="dataSourceList"
        class="j-table-force-nowrap"
      >

        <template slot="type" slot-scope="text, record, index">
          <a-radio-group v-model="record.type" @change="e => handleChange(e.target.value, index, 'type')">
            <a-radio :style="radioStyle" :value="0">
              指标
            </a-radio>
            <a-radio :style="radioStyle" :value="1">
              维度
            </a-radio>
          </a-radio-group>
        </template>

         <template slot="dimensionType" slot-scope="text, record, index">
           <a-select
              v-if="record.type === 1"
              v-model="record.dimensionType"
              show-search
              option-filter-prop="children"
              :filter-option="selectFilter"
              placeholder="请选择维度"
              :options="record.dataType && record.dataType.toUpperCase() === 'DATE' ? dimensionOptions : dimensionSpecialOptions"
              @change="e => handleChange(e, index, 'dimensionType')"
            >
            </a-select>
         </template>

        <template slot="dimensionTypeTime" slot-scope="text, record, index">
          <j-dict-select-tag
            v-model="record.dimensionTypeTime"
            dictCode="dimension_date_type"
            :triggerChange="true"
            placeholder="请选择时间维度类型"
            @change="e => handleChange(e, index, 'dimensionTypeTime')"
            v-if="record.isDate === 1 && record.type === 1"
          />
        </template>

        <template slot="name" slot-scope="text, record">
          <a-input
            v-if="record.type === 0"
            v-model="record.remark"
          />
        </template>

        <template slot="remark" slot-scope="text, record">
          <a-input
            v-if="record.type === 0"
            v-model="record.remark"
          />
        </template>

        <template slot="unit" slot-scope="text, record">
          <a-input
            v-if="record.type === 0"
            v-model="record.unit"
          />
        </template>

        <template slot="isPercent" slot-scope="text, record, index">
          <a-switch
            v-if="record.type === 0"
            v-model="record.isPercent"
            @change="e => handleChange(e, index, 'isPercent')"
          />
        </template>

        <template slot="groupType" slot-scope="text, record, index">
          <a-select
              v-if="record.type === 0"
              v-model="record.groupType"
              placeholder="请选择指标聚合方式"
              :options="groupTypeOptions"
              :disabled="record.isPercent"
              @change="e => handleChange(e, index, 'groupType')"
            >
          </a-select>
        </template>

        <!-- <span slot="dimensionInfoVoList" slot-scope="dimensionInfoVoList">
          <a-tag
            style="font-size: 14px; margin-top: 5px"
            v-for="(topic, index) in dimensionInfoVoList"
            :key="index"
            color="blue"
          >{{ topic.name }}</a-tag
          >
        </span>

        <span slot="indexInfoVoList" slot-scope="indexInfoVoList">
          <a-tag
            style="font-size: 14px; margin-top: 5px"
            v-for="(topic, index) in indexInfoVoList"
            :key="index"
            color="blue"
          >{{ topic.name }}</a-tag
          >
        </span> -->

        <!-- <span slot="status" slot-scope="status">
          {{ status == 1 ? '启用' : '禁用' }}
        </span> -->

        <!-- 状态渲染模板 -->
        <!-- <template slot="status" slot-scope="status">
          <a-tag v-if="status==0" color="red">停用</a-tag>
          <a-tag v-if="status==1" color="green">启用</a-tag>
        </template> -->

        <span slot="action" slot-scope="text, record, index" class="operate-box">
          <!-- <a @click="handleOther(record)">指标标签</a> -->
          <a @click="handleDelete(index)">删除</a>
        </span>

      </a-table>
    </div>
</template>

<script>
/*
*维度指标没有name,labels是标签用逗号分割
*/
import { selectFilter } from '@/utils/util'

export default {
  name: 'IndexListStep',
  components: { },
  data() {
    return {
      dataSourceList: [],
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '数据源',
          align: 'center',
          dataIndex: 'dataSourceName',
          width: 200
        },
        {
          title: '表名',
          align: 'center',
          dataIndex: 'tableName',
          width: 200
        },
        {
          title: '字段名',
          align: 'center',
          dataIndex: 'tableColumn'
        },
        {
          title: '维度/指标',
          align: 'center',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '对应维度',
          align: 'center',
          dataIndex: 'dimensionType',
          scopedSlots: { customRender: 'dimensionType' },
          width: 200
        },
        {
          title: '时间维度类型',
          align: 'center',
          dataIndex: 'dimensionTypeTime',
          scopedSlots: { customRender: 'dimensionTypeTime' },
          width: 200
        },
        {
          title: '指标名称',
          align: 'center',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
          width: 200
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'remark' },
          width: 200
        },
        {
          title: '统计单位',
          align: 'center',
          dataIndex: 'unit',
          scopedSlots: { customRender: 'unit' }
        },
        {
          title: '是否率值',
          align: 'center',
          dataIndex: 'isPercent',
          scopedSlots: { customRender: 'isPercent' }
        },
        {
          title: '聚合方式',
          align: 'center',
          dataIndex: 'groupType',
          scopedSlots: { customRender: 'groupType' },
          width: 200
        },
        {
          title: '数据类型',
          align: 'center',
          dataIndex: 'dataType'
        },
        {
          title: '长度',
          align: 'center',
          dataIndex: 'columnLength'
        },
        {
          title: '小数位数',
          align: 'center',
          dataIndex: 'scale'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      radioStyle: {
        padding: '0 5px'
      },
      // 维度下拉框
      dimensionOptions: [],
      dimensionSpecialOptions: [],
      // 聚合方式下拉框
      groupTypeOptions: [],
      tableHeight: 706
    }
  },
  created() {
    this.loadDimensionOptions()
    this.loadGroupTypeOptions()
  },
  mounted() {
    // 获取容器当前高度，重设表格的最大高度
    this.getTableMaxHeight()
    window.onresize = () => {
      this.getTableMaxHeight()// 获取容器当前高度，重设表格的最大高度
    }
  },
  methods: {
    selectFilter,
    setData(data) {
      this.dataSourceList = data
    },
    // 获取容器当前高度，重设表格的最大高度
    getTableMaxHeight() {
      this.$nextTick(() => {
        if (document.querySelector('.index-step-container') === null) return
        const box = document.querySelector('.index-step-container').attributes
        const boxHeight = box[0].ownerElement.clientHeight - 20 - 50
        this.tableHeight = boxHeight
      })
    },
    loadDimensionOptions() {
      this.$get('/dimension/scSituationDimensionType/list?pageNo=1&pageSize=1000&status=1').then(res => {
        this.dimensionOptions = [
          {
            value: 'time',
            title: '时间维度'
          }
        ]
        res.result.records.map(item => {
          this.dimensionOptions.push({
            value: item.id,
            title: item.dimensionName
          })
        })
        this.dimensionSpecialOptions = JSON.parse(JSON.stringify(this.dimensionOptions))
        this.dimensionSpecialOptions[0].disabled = true
      })
    },
    loadGroupTypeOptions() {
      this.$get('/sys/dict/getDictItems/index_group_type').then(res => {
        res.result.map(item => {
          if (item.status) {
            this.groupTypeOptions.push({
              value: item.value,
              title: item.text
            })
          }
        })
      })
    },
    handleOther(record) {

    },
    handleDelete(index) {
      this.dataSourceList.splice(index, 1)
    },
    handleChange(value, index, name) {
      if (name === 'dimensionType') {
        if (value === 'time') {
          this.dataSourceList[index].isDate = 1
        } else {
          this.dataSourceList[index].isDate = 0
        }
      }
      if (name === 'dimensionTypeTime') this.dataSourceList[index].dimensionTypeTime = value
      if (name === 'isPercent') this.dataSourceList[index].groupType = undefined
      this.dataSourceList = [...this.dataSourceList]
    },
    // 检查数据状态，optType=2 测试sql语句， optType=1 保存
    checkData(optType = 1) {
      let record = this.dataSourceList.find(item => item.type === 1 && item.dimensionType === undefined)

      if (record) {
        this.$message.warning(`${record.tableName}表的${record.tableColumn}字段未选择对应维度`)
        return
      }

      record = this.dataSourceList.find(item => item.type === 1 && item.dimensionType === 'time' && item.dimensionTypeTime === undefined)

      if (record) {
        this.$message.warning(`${record.tableName}表的${record.tableColumn}字段未选择时间维度类型`)
        return
      }

      record = this.dataSourceList.find(item => item.type === 0 && item.name.trim() === '')
      if (record) {
        this.$message.warning(`${record.tableName}表的${record.tableColumn}字段未输入指标名称`)
        return
      }

      record = this.dataSourceList.find(item => item.type === 0 && !item.isPercent && item.groupType === undefined)
      if (record) {
        this.$message.warning(`${record.tableName}表的${record.tableColumn}字段未选择聚合方式`)
        return
      }

      const dimensionInfos = []
      const indexInfos = []
      this.dataSourceList.map(item => {
        if (item.type === 0) {
          const obj = {
            columnId: item.columnId,
            columnLength: item.columnLength,
            dataSource: item.dataSource,
            dataType: item.dataType,
            groupType: item.groupType,
            isPercent: item.isPercent ? 1 : 0,
            labels: item.labels,
            name: item.name,
            remark: item.remark,
            scale: item.scale,
            tableColumn: item.tableColumn,
            tableName: item.tableName,
            unit: item.unit
          }

          if (obj.scale === undefined) delete obj.scale

          indexInfos.push(obj)
        } else {
          const obj = {
            columnId: item.columnId,
            columnLength: item.columnLength,
            dataSource: item.dataSource,
            dataType: item.dataType,
            groupType: item.groupType,
            dimensionType: item.isDate === 0 ? item.dimensionType : item.dimensionTypeTime,
            isDate: item.isDate,
            tableColumn: item.tableColumn,
            tableName: item.tableName
          }

          dimensionInfos.push(obj)
        }
      })
      if (indexInfos.length === 0) {
        this.$message.warning('请至少保留一个非维度指标')
        return
      }
      if (dimensionInfos.length === 0) {
        this.$message.warning('请至少选择一个指标作为维度')
        return
      }
      this.$emit('ok', { dimensionInfos, indexInfos, optType })
    }
  }
}
</script>
<style lang="less" scoped>
.index-list-step-container {
    position: relative;
    height: 100%;
    // overflow: hidden;
}
</style>
<style lang="less">
  .index-list-step-container {
    .operate-box {
        a {
            margin: 0 6px;
        }
    }

    td>.ant-select {
      min-width: 180px;
    }

    .j-table-force-nowrap td, .j-table-force-nowrap th {
      white-space: normal;
    }
}
</style>
